<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>角色管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <script type="text/html" id="toolBar">
          <div class="layui-btn-group">
            <a class="layui-btn layui-btn-sm data-count-add" lay-event="add">添加</a>
          </div>
		    </script>
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="enableTpl">
          <input type="checkbox" name="enable" value="{{d.id}}" lay-skin="switch" lay-text="是|否" lay-filter="enableSwitch" {{ d.enable == 1 ? 'checked' : '' }}>
      </script>
      
      <!-- 操作列 -->
      <script type="text/html" id="tableBar">
          <a class="layui-btn layui-btn layui-btn-xs" lay-event="dispatch">分配权限</a>
          <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="update">修改信息</a>
          <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
      </script>

      <!--添加和修改的弹出层开始-->
      <div id="addOrUpdateDiv" style="display: none;padding: 0.3125rem">
        <form method="post" class="layui-form" lay-filter="dataFrm" id="dataFrm">
          <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
              <input type="hidden" name="id" />
              <input type="text" name="name" lay-verify="required" autocomplete="off" placeholder="请输入角色名称" class="layui-input">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
              <textarea name="remark" placeholder="请输入备注内容" class="layui-textarea"></textarea>
            </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
              <a class="layui-btn " lay-submit=""  lay-filter="doSubmit"><label class="layui-icon layui-icon-release"></label>提交</a>
              <a class="layui-btn layui-btn-warm" onclick="javascript:$('#dataFrm')[0].reset()" lay-filter="data-search-btn"><label class="layui-icon layui-icon-refresh"></label>重置</a>
            </div>
          </div>
        </form>
      </div>
      <!--添加和修改的弹出层结束-->

      <div id="dispatchDiv" style="display: none;padding: 0.3125rem">
        <form method="post" class="layui-form" lay-filter="dataFrm" id="dataFrm">
          <div class="layui-form-item">
            <label class="layui-form-label">角色名称</label>
            <div class="layui-input-block">
              <input type="hidden" name="id" />
              <input type="text" name="name" readonly lay-verify="required" autocomplete="off" placeholder="请输入角色名称" class="layui-input">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">分配权限</label>
            <div class="layui-input-block">
              <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                <ul class="layui-tab-title">
                  <li class="layui-this">可见菜单</li>
                  <li>可用权限</li>
                </ul>
                <div class="layui-tab-content">
                  <div class="layui-tab-item layui-show">
                    <table id="menu-table" class="layui-table" lay-filter="menu-table"></table>
                  </div>
                  <div class="layui-tab-item">
                    <table id="permission-table" class="layui-table" lay-filter="permission-table"></table>
                  </div>
                </div>
              </div>      
            </div>
          </div>
          <div class="layui-form-item">
            <div class="layui-input-block" style="text-align: right;">
              <a class="layui-btn " lay-submit=""  lay-filter="doDispatch"><label class="layui-icon layui-icon-release"></label>提交</a>
            </div>
          </div>
        </form>
      </div>

    </div>
</div>

<script src="/lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/lib/common/jquery.cookie.min.js" charset="utf-8"></script>
<script src="/lib/common/common.js" charset="utf-8"></script>
<script>
    layui.use(['element', 'form', 'table', 'treeTable'], function () {
      var $ = layui.jquery,
          form = layui.form,
          table = layui.table;
      var table1 = layui.table;
      var element = layui.element;
      var treeTable = layui.treeTable;

      var tableIns = table.render({
          elem: '#currentTableId',
          url: api + '/role/getByPage',
          method: 'post',
          contentType: "application/json; charset=utf-8",
          toolbar:"#toolBar",
          cellMinWidth: true,
          parseData: function(res){ //res 即为原始返回的数据
            return {
              "code": res.code, //解析接口状态
              "msg": res.msg, //解析提示文本
              "count": res.data.total, //解析数据长度
              "data": res.data.records //解析数据列表
            };
          },
          response:{ // 必须配置，否则不加载数据
            statusName:'code', //规定返回的状态码字段为code
            statusCode:200 //规定成功的状态码味200
          },
          cols: [[
            {type: "numbers", width: 40, title: '序号', fixed: "left"},
            {field: 'id', width: 80, title: 'ID', hide: true},
            {field: 'name', minWidth: 100, title: '角色名称'},
            {field: 'enable',  title: '是否启用', align: "center",width: 120,templet:'#enableTpl'},
            {field: 'createTime', minWidth: 100, title: '创建时间'},
            {field: 'remark', minWidth: 200, title: '备注'},
            {title: '操作', minWidth: 200, templet: '#tableBar', fixed: "right", align: "center"}
          ]],
          limits: [10, 15, 20, 25, 5],
          limit: 15,
          page: true
      });

      // 渲染表格
      var menuTableIns = treeTable.render({
        elem: '#menu-table',
        url: api + '/menu/loadMenuList',
        page: false,
        height: '325px',
        tree: {
          iconIndex: 2,  // 折叠图标显示在第几列
          idName: 'id',  // 自定义id字段的名称
          pidName: 'pid',  // 自定义标识是否还有子节点的字段名称
          isPidData: true,  // 是否是pid形式数据
          openName: 'spread'   // 自定义默认展开的字段名
        },
        cols: [[
          {type: "checkbox", width: 50, fixed: "left"},
          {type: 'numbers'},
          {field: 'title', minWidth: 200, title: '部门名称'},
          {field: 'address', title: '部门地址'},
          {field: 'remark', title: '备注'}
        ]],
        done: function () {
          layer.closeAll('loading');
        },
        parseData: function(res) {
          return {
            "code": res.code == 200? 0 : res.code,
            "data": res.data,
            "msg": res.msg //解析提示文本
          };
        }
      });

      var permissionTableIns = treeTable.render({
        elem: '#permission-table',
        url: api + '/permission/loadAllPermission',
        page: false,
        height: '325px',
        tree: {
          iconIndex: 2,  // 折叠图标显示在第几列
          idName: 'id',  // 自定义id字段的名称
          pidName: 'pid',  // 自定义标识是否还有子节点的字段名称
          isPidData: true,  // 是否是pid形式数据
          openName: 'spread'   // 自定义默认展开的字段名
        },
        cols: [[
          {type: "checkbox", width: 50, fixed: "left"},
          {type: "numbers", width: 40, fixed: "left"},
          {field: 'id', width: 80, title: 'ID', hide: true},
          {field: 'name', minWidth: 100, title: '权限名称'},
          {field: 'module', minWidth: 200, title: '权限模块'},
          {field: 'operationType', minWidth: 100, title: '权限类型'},
          {field: 'permissionUri', minWidth: 120, title: '权限URI'}
        ]],
        done: function () {
          layer.closeAll('loading');
        },
        parseData: function(res) {
          return {
            "code": res.code == 200? 0 : res.code,
            "data": res.data,
            "msg": res.msg //解析提示文本
          };
        }
      });

      // 监听搜索操作
      form.on('submit(data-search-btn)', function (data) {
          //执行搜索重载
          table.reload('currentTableId', {
            page: {
              curr: 1
            },
            where: {
              queryParams: {
              }
            },
            async: true
          }, 'data');

          return false;
      });

      //监听启用操作
      form.on('switch(enableSwitch)', function(obj){
        $.ajax({
            url: api + (obj.elem.checked? "/role/enable" : "/role/disable") + "/" + this.value,
            method: "put",
            async: true,
            success:function(res){
                layer.msg(res.msg);
                // tableIns.reload();
            },
            error:function(){
                layer.msg("操作失败");
            }
        });
	     });

      //提交数据
      form.on("submit(doSubmit)",function(data){
        let params = {
          "id": data.field.id,
          "name": data.field.name,
          "remark": data.field.remark
        };
        $.ajax({
          url: url,
          method: formState === FORM_ADD? "post" : "put",
          async: true,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: JSON.stringify(params),
          success:function(res){
            layer.msg(res.msg);
            tableIns.reload();
          },
          error:function(){
            layer.msg("操作失败");
          }
        });
        layer.close(mainIndex);
        return false;
      });

      form.on("submit(doDispatch)",function(data){
        var permissionCheck = permissionTableIns.checkStatus();
        var menuCheck = menuTableIns.checkStatus();
        var permissions = [], menus = [];
        //遍历
        permissionCheck.forEach(function(item){
          permissions.push(item.id)
        });
        menuCheck.forEach(function(item){
          menus.push(item.id)
        });
        let params = {
          'rid': data.field.id,
          'permissions': permissions,
          'menus': menus
        };
        $.ajax({
          url: api + "/role/dispatchMenuAndPermission",
          method: "put",
          async: true,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          data: JSON.stringify(params),
          success:function(res){
            layer.msg(res.msg);
            //tableIns.reload();
          },
          error:function(){
            layer.msg("操作失败");
          }
        });
        layer.close(mainIndex);
        return false;
      })
 
      //监听表头的事件
      table.on('toolbar(currentTableFilter)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id);
        switch(obj.event){
          case 'add':
            openAddRole();
          break;
        };
      });

      //监听行数据的事件
      table.on('tool(currentTableFilter)', function (obj) {
        var data = obj.data;
        switch(obj.event) {
          case 'update':
            openUpdateRole(data);
            break;
          case 'delete':
            deleteObj(obj);
            break;
          case 'dispatch':
            dispatchPermission(obj);
            break;
        }
      });

      //打开添加的弹层
      var mainIndex;
      var url;  //动态的url
      var formState;
      function openAddRole(){
        mainIndex=layer.open({
          type:1,
          title:'添加角色',
          content:$("#addOrUpdateDiv"),
          area:['400px','275px'],
          success:function(index){
            formState = FORM_ADD;
            url=api + "/role/addRole";
            //重置表单
            $("#dataFrm")[0].reset();
          }
        });	
      };

      function openUpdateRole(data) {
        mainIndex=layer.open({
          type:1,
          title:'修改角色',
          content:$("#addOrUpdateDiv"),
          area:['400px','275px'],
          success:function(index){
            formState = FORM_UPDATE;
            url=api + "/role/updateById";
            //装载数据表格
            form.val("dataFrm",data);
          }
        });	
      };

      function deleteObj(obj) {
        layer.confirm('真的要删除角色【'+obj.data.name+'】吗?', function (index) {
          $.ajax({
            url: api + '/role/deleteById',
            method: 'delete',
            async: true,
            data: {'id':obj.data.id},
            success:function(resp){
                layer.msg(resp.msg);
                if(resp.code === SUCCESS_CODE) {
                    obj.del();
                }
            },
            error:function(){
                layer.msg("接口访问异常");
            }
          });
        });
      };

      function dispatchPermission(obj) {
        mainIndex=layer.open({
          type:1,
          title:'分配权限',
          content:$("#dispatchDiv"),
          area:['800px','625px'],
          success:function(index){
            //装载数据表格
            permissionTableIns.removeAllChecked();
            menuTableIns.removeAllChecked();
            form.val("dataFrm", obj.data);
            $.get(api + '/role/getMenuAndPermission', {rid: obj.data.id}, function(resp) {
              if(resp.code === SUCCESS_CODE) {
                permissionTableIns.setChecked(resp.data.permissions);
                menuTableIns.setChecked(resp.data.menus);
              }
            });
          }
        });	
      };
    });
</script>
<script>

</script>

</body>
</html>